package org.hbhk.hxl.gateway.filter;

import org.hbhk.hxl.gateway.exception.RouteException;
import org.hbhk.hxl.gateway.model.HttpService;
import org.hbhk.hxl.gateway.route.SystemClock;
import org.hbhk.hxl.gateway.services.ServiceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.NettyWriteResponseFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;

/**
 * 
 * 服务的开启和关闭管理
 *
 */
@Component
public class GatewayFilter implements GlobalFilter, Ordered {

	private final Logger logger = LoggerFactory.getLogger(GatewayFilter.class);

	private static final String START_TIME = "startTime";

	public static final String GATEWAY_REQUEST_URL_ATTR_SURL = "gateway_request_url_attr_surl";

	public static final String GATEWAY_REQUEST_ROUTE_URL = "gateway_request_route_url";

	@Override
	public int getOrder() {
		return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER - 10;
	}

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		ServerHttpRequest request = exchange.getRequest();
		String url = request.getURI().getPath();

		exchange.getAttributes().put(START_TIME, SystemClock.now());
		HttpService httpService = ServiceUtil.getHttpService(url);
		if (httpService == null) {
			throw new RouteException("服务不存在:" + url);
		}
		boolean like = httpService.isLike();
		if (like) {
			exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR_SURL, httpService.getUrl());
		} else {
			exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR_SURL, url);
		}
		if ("0".equals(httpService.getEnable())) {
			String info = httpService.getInfo();
			if (!StringUtils.isEmpty(info)) {
				throw new RouteException(info);
			}
			throw new RouteException("服务被禁用:" + url);
		}
		return chain.filter(exchange).then(Mono.fromRunnable(() -> {
			Long startTime = exchange.getAttribute(START_TIME);
			if (startTime != null) {
				Long executeTime = (SystemClock.now() - startTime);
				String routeUrl = exchange.getRequiredAttribute(GatewayFilter.GATEWAY_REQUEST_ROUTE_URL);
				logger.info(
						exchange.getRequest().getURI().getRawPath() + " to " + routeUrl + " : " + executeTime + "ms");
			}
		}));

	}

}